<template>
  <div>
    <div class="card" style="margin-bottom: 5px;">
      <el-input v-model="data.name" placeholder="请输入电影名称查询" style="width: 300px; margin-right: 10px"></el-input>
      <el-button type="primary" @click="load">查询</el-button>
      <el-button type="info" @click="reset">重置</el-button>
      <el-button type="warning" @click="handleAdd">新增</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-button :class="{ 'film-active' : data.categoryId === null}" @click="loadFilmByCategory(null)">全部</el-button>
      <el-button v-for="item in data.categoryList" :key="item.id" @click="loadFilmByCategory(item.id)" :class="{ 'film-active' : data.categoryId === item.id}">{{ item.name }}</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px;">
      <el-row :gutter="20">
        <el-col :span="6" v-for="item in data.tableData" :key="item.id" style="margin-bottom: 20px;">
          <img :src="item.cover" alt="" @click="goDetail(item.id)" style="width: 100%; height: 500px; border-radius: 5px; margin-bottom: 5px; cursor: pointer;">
          <span class="span-align">
            <img style="width: 25px; height: 25px; border-radius: 50%; margin-right: 5px; cursor: pointer;" @click="goUserDetail(item.userId)" :src="item.userAvatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" alt="">
            <span style="font-size: 14px; color: pink;">{{ item.userName }}</span>
            <span style="font-size: 13px; color: grey">大力推荐</span>
          </span>
          <div style="margin-top: 10px; margin-bottom: 5px; font-size: 18px; font-weight: bold;" class="line1">{{ item.name }}</div>
          <div style="font-size: 13px; color: #666" class="line3">{{ item.descr }}</div>
        </el-col>
      </el-row>
    </div>

    <el-pagination background layout="->, total, prev, pager, next" v-model:page-size="data.pageSize"
                   v-model:current-page="data.pageNum" :total="data.total" @current-change="load"></el-pagination>

    <!--弹窗-->
    <el-dialog v-model="data.formVisible" title="电影信息" width="40%">
      <el-form ref="ruleFormRef" :model="data.form" :rules="rules" label-width="80px" style="padding-right: 20px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="data.form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="封面" prop="cover">
          <el-upload v-model="data.form.cover" ref="uploadRef" :action="uploadUrl" list-type="picture" :on-success="handleImgSuccess" :limit="1" :on-exceed="handleExceed">
            <el-button type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="简介" prop="descr">
          <el-input :rows="5" type="textarea" v-model="data.form.descr" autocomplete="off" placeholder="请输入电影简介" />
        </el-form-item>
        <el-form-item label="导演" prop="director">
          <el-input v-model="data.form.director" autocomplete="off" placeholder="请输入导演" />
        </el-form-item>
        <el-form-item label="编剧" prop="screenwriter">
          <el-input v-model="data.form.screenwriter" autocomplete="off" placeholder="请输入编剧" />
        </el-form-item>
        <el-form-item label="主演" prop="actors">
          <el-input :rows="4" type="textarea" v-model="data.form.actors" autocomplete="off" placeholder="请输入主演" />
        </el-form-item>
        <el-form-item label="类型" prop="categoryName">
          <el-radio-group v-for="item in data.categoryList" :key="item.id" v-model="data.form.categoryName" @change="changeCategoryId">
            <el-radio style="margin-right: 20px;" :label=item.id>{{ item.name }}</el-radio>
          </el-radio-group>
          <el-popover :visible="data.addCategoryVisible" placement="right" :width="150">
            <el-input v-model="data.categoryName.name" autocomplete="off" placeholder="请输入类型名称" />
            <div style="margin-top: 10px;">
              <el-button size="small" text @click="data.addCategoryVisible = false">取消</el-button>
              <el-button size="small" type="primary" @click="addCategory">确定</el-button>
            </div>
            <template #reference>
              <el-button @click="data.addCategoryVisible = true">添加类型</el-button>
            </template>
          </el-popover>
        </el-form-item>
        <el-form-item label="国家" prop="country">
          <el-input v-model="data.form.country" autocomplete="off" placeholder="请输入制片国家" />
        </el-form-item>
        <el-form-item label="语言" prop="language">
          <el-input v-model="data.form.language" type="language" autocomplete="off" placeholder="请输入语言" />
        </el-form-item>
        <el-form-item label="上映日期" prop="date">
          <el-date-picker style="width: 100%" type="date" v-model="data.form.date" placeholder="请选择上映日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
        </el-form-item>
        <el-form-item label="上映年份" prop="year">
          <el-date-picker style="width: 100%" type="year" v-model="data.form.year" placeholder="请选择上映年份" format="YYYY年" value-format="YYYY年"></el-date-picker>
        </el-form-item>
        <el-form-item label="片长" prop="duration">
          <el-input v-model="data.form.duration" autocomplete="off" placeholder="请输入片长" />
        </el-form-item>
        <el-form-item label="IMDb" prop="imdb">
          <el-input v-model="data.form.imdb" autocomplete="off" placeholder="请输入IMDb" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button plain type="primary" @click="save">保 存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {reactive, ref} from "vue";
import request from "@/utils/request";
import {ElMessage} from "element-plus";

const data = reactive({
  tableData: [],
  pageNum: 1,
  pageSize: 4,
  total: 0,
  name: null,
  categoryList: [],
  categoryId: null,
  categoryName: {},
  addCategoryVisible: false,
  user: JSON.parse(localStorage.getItem('system-user') || '{}'),
})

//新增校验规则
const ruleFormRef = ref(null)
const rules = {
  name: [{ required: true, message: '电影名称不能为空', trigger: 'blur' }],
  cover: [{ required: true, message: '未上传电影封面', trigger: 'blur' }],
  descr: [{ required: true, message: '电影简介不能为空', trigger: 'blur' }],
  screenwriter: [{ required: true, message: '电影编剧不能为空', trigger: 'blur' }],
  director: [{ required: true, message: '电影拍摄导演不能为空', trigger: 'blur' }],
  actors: [{ required: true, message: '电影主演不能为空', trigger: 'blur' }],
  categoryName: [{ required: true, message: '必须选择一个类型', trigger: 'change' }],
  country: [{ required: true, message: '电影制片国家不能为空', trigger: 'blur' }],
  language: [{ required: true, message: '电影语言不能为空', trigger: 'blur' }],
  date: [{ required: true, message: '未选择电影上映日期', trigger: 'blur' }],
  year: [{ required: true, message: '未选择电影上映年份', trigger: 'blur' }],
  duration: [{ required: true, message: '电影片长不能为空', trigger: 'blur' },
    { pattern: /^\d+分钟$/, message: '请输入以“分钟”结尾的片长', trigger: 'blur' }],
  imdb: [{ required: true, message: '电影IMDb值不能为空', trigger: 'blur' }],
}

//跳转到用户主页
const goUserDetail = (id) => {
  location.href = '/userView?id=' + id
}

const changeCategoryId = (val) => {
  data.form.categoryId = val
}

// 加载分类列表
const loadCategoryList = () => {
  request.get("/category/selectAll").then(res => {
    if(res.code === '200'){
      data.categoryList = res.data
    }else{
      ElMessage.error(res.msg)
    }
  })
}
loadCategoryList()

// 新增类型名
const addCategory = () =>{
  if(!data.categoryName.name){
    ElMessage.error('请输入类型名称')
  }else{
    request.post('/category/add', data.categoryName).then((res) => {
      if(res.code === '200'){
        loadCategoryList()
        data.addCategoryVisible = false
        ElMessage.success('操作成功')
      }else{
        ElMessage.error(res.msg)
      }
    })
  }
}

// 根据categoryId查询电影
const loadFilmByCategory = (categoryId) => {
  data.categoryId = categoryId
  load()
}

// 查询电影列表
const load = () => {
  request.get('/film/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      name: data.name,
      categoryId: data.categoryId,
    }
  }).then(res => {
    data.tableData = res.data?.list
    data.total = res.data?.total
  })
}
load()

// 新增
const handleAdd = () => {
  loadCategoryList()
  data.form = {}
  data.formVisible = true
}
// 新增保存
const save = () => {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.validate((valid) => {
    if(valid){
      data.form.userId = data.user.id
      request.post('/film/add', data.form).then(res => {
        if (res.code === '200') {
          data.formVisible = false
          ElMessage.success('操作成功')
          load()
        } else {
          ElMessage.error(res.msg)
        }
      })
    }else{
      ElMessage.error('请填写必填项')
    }
  })
}

const goDetail = (id) => {
  location.href = '/filmDetail?id=' + id
}

const reset = () => {
  data.name = null
  load()
}

// 文件上传的接口地址
const uploadUrl = import.meta.env.VITE_BASE_URL + '/files/upload'
const uploadRef = ref(null);
// 处理文件上传的钩子
const handleImgSuccess = (res) => {
  data.form.cover = res.data  // res.data就是文件上传返回的文件路径，获取到路径后赋值表单的属性
}

// 生成UID
const genFileId = () => Math.random().toString(36).substring(7);

// 限制上传头像数量
const handleExceed = (files, fileList) => {
  const upload = uploadRef.value;
  if (upload) {
    upload.clearFiles();
    const file = files[0];
    file.uid = genFileId();
    upload.handleStart(file);
  }
}
</script>

<style scoped>
.film-active {
  background-color: mediumseagreen;
  color: white;
}
</style>